//
//  MSNetEngine.m
//  MyShare
//
//  Created by koki on 15/9/14.
//  Copyright (c) 2015年 MyShare. All rights reserved.
//

#if defined TEST

#elif defined PREPRODUCT

#elif defined PRODUCT


#endif


#import "MSNetEngine.h"

@interface MSNetEngine ()
@property(nonatomic,strong)AFHTTPRequestOperationManager *operationManager;
@end

@implementation MSNetEngine


static MSNetEngine* instance=nil;
+(MSNetEngine*)sharedInstance
{
    @synchronized(self)
    {
        if(instance==nil)
        {
            instance= [[self alloc]init];
        }
    }
    return instance;
}

- (id)init
{
    self=[super init];
    if (self) {
        self.netQueue = [[NSOperationQueue alloc] init];
    }
    return self;
}

- (void)showErrorMessge:(NSError*)error {
    if (error) {
        NSData *responseData = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (responseData) {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:NULL];
            NSString *errorMsg = [HDUtil check:response[@"message"]];
            if (errorMsg==nil||!errorMsg.length) {
                if ([self checkSessionId:error]) {
                    [HDUtil showMessage:@"服务器忙，请稍后再试~"];
                }
                NSLog(@"11111111");
            } else {
                [[[UIAlertView alloc] initWithTitle:@"提示" message:errorMsg delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil] show];
            }
        } else {
            if (![AFNetworkReachabilityManager sharedManager].reachable) {
                if ([self checkSessionId:error]) {
                    [HDUtil showMessage:@"网络不给力，请稍后再试~"];
                }
                NSLog(@"222222222");
            } else {
                [HDUtil showMessage:@"服务器忙，请稍后再试~"];
                NSLog(@"3333333");
            }
        }
    } else {
        [HDUtil showMessage:@"服务器忙，请稍后再试~"];
        NSLog(@"4444444");
    }
}

- (BOOL)checkSessionId:(id)errorInfo
{
    if (errorInfo) {
        if ([errorInfo isKindOfClass:[NSURLSessionDataTask class]]) {
            NSURLSessionDataTask* task = (NSURLSessionDataTask *)errorInfo;
            NSHTTPURLResponse* r = (NSHTTPURLResponse*)task.response;
            NSLog(@"AAAA失效了%ld",r.statusCode);
            if (r.statusCode==401) {
                NSLog(@"sessionId失效了");
                [self quitClick];
                return NO;
            }
        } else if ([errorInfo isKindOfClass:[AFHTTPRequestOperation class]]) {
            AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)errorInfo;
            NSHTTPURLResponse* r = (NSHTTPURLResponse*)operation.response;
            NSLog(@"BBBBB失效了%ld",r.statusCode);
            if (r.statusCode==401) {
                NSLog(@"sessionId失效了");
                [self quitClick];
                return NO;
            }
        } else if ([errorInfo isKindOfClass:[NSURLResponse class]]) {
            NSHTTPURLResponse* r = (NSHTTPURLResponse*)errorInfo;
            NSLog(@"CCCCCCC失效了%ld",r.statusCode);
            if (r.statusCode==401) {
                NSLog(@"sessionId失效了");
//                [self quitClick];
                return NO;
            }
        }
    }
    return YES;
}

- (void)quitClick{
    [HDUtil showMessage:@"已过期，请重新登录"];
    
    NSUserDefaults *defaultes = [NSUserDefaults standardUserDefaults];
    [defaultes setObject:@"" forKey:LoginState];
    [defaultes setObject:@"" forKey:LoginSessionId];
    [defaultes synchronize];
    
    netEngine.sessionId = @"";
    [rootNavigation popToRootViewControllerAnimated:NO];
    rootDelegate.mainViewController.selectedTabBarIndex = 0;
}

- (void)GET:(NSString *)URLString
        parameters:(id)parameters
        hudView:(UIView *)hudView
        success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
        failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure
{
    [SXProgressHUD showHUDAddedTo:hudView animated:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [_operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"zh-CN" forHTTPHeaderField:@"Accept-Language"];
    
    [manager GET:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
        NSHTTPURLResponse* r = (NSHTTPURLResponse*)task.response;
        if (r.statusCode==200) {
            success(task, responseObject);
        }else {
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
        [self checkSessionId:task];
        failure(task, error);
    }];
}

//- (void)GET:(NSString *)URLString
//  parameters:(id)parameters
//     hudView:(UIView *)hudView
//     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
//     failure:(void (^)(AFHTTPRequestOperation * operation, NSError *error))failure{
//    [self.operationManager GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
//        failure(task, error);
//    }];
//
//}

- (void)POST:(NSString *)URLString
        parameters:(id)parameters
        hudView:(UIView *)hudView
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation * operation, NSError *error))failure
{
    [SXProgressHUD showHUDAddedTo:hudView animated:YES];
    
    [self.operationManager POST:URLString parameters:parameters
                        success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
         NSHTTPURLResponse* r = (NSHTTPURLResponse*)operation.response;
         if (r.statusCode==200)
         {
             success(operation, responseObject);
         } else {
             
         }
     } failure:^(AFHTTPRequestOperation * __nullable operation, NSError *error) {
         failure(operation, error);
         [self checkSessionId:operation];
         [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
     }];
}

- (void)POST:(NSString *)URLString
        parameters:(id)parameters
        hudView:(UIView *)hudView
        constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [SXProgressHUD showHUDAddedTo:hudView animated:YES];
    [self.operationManager POST:URLString parameters:parameters constructingBodyWithBlock:block success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
        NSHTTPURLResponse* r = (NSHTTPURLResponse*)operation.response;
        if (r.statusCode==200)
        {
            success(operation, responseObject);
        } else {
            
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
        failure(operation, error);
    }];
}

- (void)DELETE:(NSString *)URLString
        parameters:(id)parameters
        hudView:(UIView *)hudView
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation * operation, NSError *error))failure
{
    [SXProgressHUD showHUDAddedTo:hudView animated:YES];
    [self.operationManager DELETE:URLString parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
        NSHTTPURLResponse* r = (NSHTTPURLResponse*)operation.response;
        if (r.statusCode==200)
        {
            success(operation, responseObject);
        } else {
            
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
        failure(operation, error);
    }];
}

- (void)PUT:(NSString *)URLString
        parameters:(id)parameters
        hudView:(UIView *)hudView
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation * operation, NSError *error))failure
{
    [SXProgressHUD showHUDAddedTo:hudView animated:YES];
    
    [self handleAFSerializer:URLString];
    [self.operationManager PUT:URLString parameters:parameters
                       success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
         NSHTTPURLResponse* r = (NSHTTPURLResponse*)operation.response;
         if (r.statusCode==200)
         {
             success(operation, responseObject);
         } else {
             
         }
         
     } failure:^(AFHTTPRequestOperation * __nullable operation, NSError *error) {
         [SXProgressHUD hideAllHUDsForView:hudView animated:YES];
         failure(operation, error);
     }];
}

- (AFHTTPRequestOperationManager *)operationManager
{
    if (!_operationManager) {
        _operationManager = [AFHTTPRequestOperationManager manager];
        _operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _operationManager.responseSerializer.acceptableContentTypes = [_operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
        [_operationManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [_operationManager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [_operationManager.requestSerializer setValue:@"zh-CN" forHTTPHeaderField:@"Accept-Language"];
    }//text/html   application/Json   text/plain
    return _operationManager;
}

- (NSMutableDictionary *)requestSerializerDic
{
    if (!_requestSerializerDic) {
        _requestSerializerDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    return _requestSerializerDic;
}

- (NSMutableDictionary *)responseSerializerDic
{
    if (!_responseSerializerDic) {
        _responseSerializerDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    return _responseSerializerDic;
}

#pragma mark - private method
- (void)handleAFSerializer:(NSString *)URLString
{
    if (_requestSerializerDic && _requestSerializerDic[[HDUtil check:URLString]]) {
        AFHTTPRequestSerializer *requestSerializer = _requestSerializerDic[[HDUtil check:URLString]];
        if ([requestSerializer isKindOfClass:[AFHTTPRequestSerializer class]]) {
            self.operationManager.requestSerializer = requestSerializer;
        }
    } else {
        self.operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    if (_responseSerializerDic && _responseSerializerDic[[HDUtil check:URLString]]) {
        AFHTTPResponseSerializer *responseSerializer = _responseSerializerDic[[HDUtil check:URLString]];
        if ([responseSerializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
            self.operationManager.responseSerializer = responseSerializer;
        }
    } else {
        self.operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    }
    [self.operationManager.requestSerializer setValue:@"zh-CN" forHTTPHeaderField:@"Accept-Language"];
}

@end
















